package com.mj.factory.workOrder;

import com.mj.factory.processFlow.ProcessFlow;
import com.mj.factory.processFlow.ProcessFlowController;
import com.mj.factory.processFlow.ProcessFlowService;
import com.mj.factory.processFlow.Technology.ExportExcel;
import com.mj.factory.productOrder.ProductOrder;
import com.mj.factory.productOrder.ProductOrderService;
import com.mj.factory.totalSchuedule.TotalSchedule;
import com.mj.mes.excelutil.ExcelContrller;
import com.mj.mes.excelutil.ExcelUtil;

import com.mj.mes.utils.FileUtils;
import com.mj.mes.utils.IsEmpty;
import com.mj.processController.DynamicProcess;
import org.apache.commons.collections4.map.HashedMap;
import com.mj.factory.totalSchuedule.TotalScheduleService;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.mj.factory.workOrder.WorkOrderStatus.*;
import static com.mj.factory.workOrder.WorkOrderStatus.StatusEnum.*;

/**
 * Created by Administrator on 2017/3/16.
 */
@Controller
@RequestMapping("mjfactory")
public class WorkOrderController {
    private Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    WorkOrderService workOrderService;
    @Autowired
    ProcessFlowService processFlowService;
    @Autowired
    TotalScheduleService totalScheduleService;
    @Autowired
    ProcessFlowController processFlowController;
    @Autowired
    ProductOrderService productOrderService;
    @Autowired
    DynamicProcess dynamicProcess;

    //查找工单所有的信息
    @PostMapping(value = "processFlow/processFlowQueryWithPaging")
    @ResponseBody
//    @CheckPermission(permission={"mj_totalschedule:view"})
    public Map<String, Object> findAll(String findMaterialNumber ,String findPartName,String findMaterial,String findMaterialSpec,String findChartNumber,String findArrivalDate,Integer page, Integer rows, @RequestParam(value = "rows") Integer size) {
        Map<String, Object> map = new HashMap();
        Page<WorkOrder> list=null;
        if(IsEmpty.isEmpty(findMaterialNumber)&& IsEmpty.isEmpty(findPartName)&& IsEmpty.isEmpty(findMaterial)&& IsEmpty.isEmpty(findMaterialSpec)&& IsEmpty.isEmpty(findChartNumber)&& IsEmpty.isEmpty(findArrivalDate)){
            list = workOrderService.findAll(new PageRequest(page - 1, size));
            int total = workOrderService.findAll().size();
            map.put("total", total);
            map.put("rows", list.getContent());
        }else{

            List<WorkOrder> findList=workOrderService.findWorkOrderBySql(findMaterialNumber ,findPartName,findMaterial,findMaterialSpec,findChartNumber,findArrivalDate,page, rows);
            int total = findList.size();
            map.put("total", total);
            map.put("rows", findList);
        }


        return map;
    }
    /**
     * @param page,size
     * @author cRyann
     * @Description 生管获取分解后的生产任务
     **/
    @RequestMapping(value = "processController/ProcessControllerFindWithPaging")
    @ResponseBody
    public Map<String, Object> findProcessControllerTodglist(Integer page, @RequestParam(value = "rows") Integer size,
                                                             String projectName,
                                                             String partName,
                                                             String chartNumber,
                                                             String status
    ) {
        Map<String, Object> map = new HashedMap();
        projectName = (projectName != null && !projectName.equals("")) ?  "%" + projectName + "%":"%" ;
        partName = (partName != null && !partName.equals("")) ?  "%" + partName + "%":"%" ;
        chartNumber = (chartNumber != null && !chartNumber.equals("")) ? "%" + chartNumber + "%":"%" ;
        status = (status != null && !status.equals("")) ?  "%" + status + "%":"%" ;

        Page<WorkOrder> list = workOrderService.findAll(projectName, partName, chartNumber, status, new PageRequest(page - 1, size));
        map.put("total", list.getSize());
        map.put("rows", list.getContent());
        return map;
    }

    //添加工单
    @RequestMapping(value = "addWorkOrder", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addProductionProject(WorkOrder workOrder) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            workOrder = workOrderService.save(workOrder);
            map.put("msg", "success");
            map.put("project", workOrder);
        } catch (Exception e) {
            map.put("msg", "fail");
            logger.error(e);
        }
        return map;
    }

    //根据Id查找工单
    @PostMapping(value = "processFlow/findById")
    @ResponseBody
//    @CheckPermission(permission={"mj_totalschedule:view"})
    public WorkOrder findById(Long workOrderId) {
        return workOrderService.findById(workOrderId);
    }

//查找状态
//    @PostMapping(value = "querybystatus")
//    @ResponseBody
//    public Map<String, Object> querybyStatus(String status, Integer page, @RequestParam(value = "rows") Integer size) {
//        Map<String, Object> map = new HashMap();
//        Page<ProductionProject> list = workOrderService
//                .findAllByStatus(status, new PageRequest(page - 1, size));
//        int total = productionProjectService.findAll().size();
//        map.put("total", total);
//        map.put("rows", list.getContent());
//        return map;
//    }


//改变状态
    @RequestMapping(value = "processController/changeStatus", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> changeStatus(Integer id, String status) {
        Map<String, Object> map = new HashedMap();
        List<Map<String, String>> processParams = new ArrayList<>();
        WorkOrder wo = workOrderService.findById(id);
        if(null!=wo){
            List<ProcessFlow> list = processFlowService.findByWorkOrderOrderBySequenceNumber(wo.getId());
            switch (status){
                case "Stop":
                    wo.setWorkOrderStatus(Running.toString());
                    // todo  activity 启动
                    for(ProcessFlow pf : list){
                        Map<String, String> m2 = new HashMap<>();
                        m2.put("id", "task_"+String.valueOf(pf.getSequenceNumber()));
                        m2.put("name", String.valueOf(pf.getProductionProcesses()));
                        processParams.add(m2);
                    }
                    dynamicProcess.createDynamicProcess("Process_"+wo.getChartNumber(),
                            "Process_"+wo.getChartNumber(),
                            processParams);
                    break;
                case "Running":
                    wo.setWorkOrderStatus(Stop.toString());
                    //todo activity 暂停
                    break;
            }
            workOrderService.save(wo);
        }
        map.put("msg","success");
        return map;
    }

    //删除工单
    @RequestMapping(value = "processFlow/deleteWorkOrder", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> deleteWorkOrder(String ids, String chartNumbers) {
        Map<String, String> map = new HashedMap();
        String[] idArrayList = ids.split(",");
        String[] cnArrayList = chartNumbers.split(",");
        List<WorkOrder> list = new ArrayList<WorkOrder>();

        boolean tFlag = false;
        for (int i = 0; i < idArrayList.length; i++) {
            //删除工单中的流程
            List<ProcessFlow> pfList = processFlowService.findByWorkOrderId(Long.parseLong(idArrayList[i]));
            if (null != pfList) {
                tFlag = processFlowService.delete(pfList);
            }
            //删除总表
            TotalSchedule totalSchedule = totalScheduleService.findByDrawingNumber(cnArrayList[i]);
            if (null != totalSchedule) {
                totalScheduleService.delete(totalSchedule);
            }

            WorkOrder workOrder = new WorkOrder();
            workOrder.setId(Long.valueOf(idArrayList[i]));
            list.add(workOrder);
        }
        boolean flag = workOrderService.delete(list);
        if (flag && tFlag) {
            map.put("msg", "success");
        } else {
            map.put("msg", "fail");
        }
        return map;
    }

    //预修改
    @RequestMapping(value = "processFlow/toUpdate", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> toUpdateWorkOrder(Long id) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            WorkOrder workOrder = workOrderService.findById(id);
            map.put("msg", "success");
            map.put("workOrder", workOrder);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "error");
        }

        return map;
    }

    //修改工单
    @RequestMapping(value = "processFlow/update", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> update(String materialNumber, String partName, String material,
                                      String materialSpec, String chartNumber, String oderNumber, String unit, String
                                              arrivalDate, String remarksFig, long poId, long id) {
        Map<String, Object> map = new HashedMap();
        try {

            WorkOrder workOrder = workOrderService.findById(id);
            workOrder.setMaterialNumber(materialNumber);
            workOrder.setPartName(partName);
            workOrder.setMaterial(material);
            workOrder.setMaterialSpec(materialSpec);
            workOrder.setChartNumber(chartNumber);
            workOrder.setOderNumber(oderNumber);
            workOrder.setUnit(unit);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            workOrder.setArrivalDate(sdf.parse(arrivalDate));
            workOrder.setRemarksFig(remarksFig);

            ProductOrder productOrder = productOrderService.findById(poId);
            workOrder.setProductOrder(productOrder);
            workOrderService.save(workOrder);
            map.put("msg", "success");
        } catch (Exception e) {
            map.put("msg", "fail");
            logger.error(e);
        }
        return map;
    }

    //导出Excel
    @RequestMapping(value = "processFlow/export", method = RequestMethod.GET)
    @ResponseBody
    public void export(Long workOrderId, HttpServletResponse response) {
        //获取当前时间
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String currentTime = format.format(date);
        //获取表头数据
        WorkOrder workOrder = findById(workOrderId);
        //获取excel数据内容
        Map<String, Object> map =processFlowController.findAll(workOrderId);
        //表头
        String[] title = {"广西名匠智能制造有限公司", "生产工艺流程卡"};
        String[] header0 = {"项目名称:",workOrder.getProductOrder().getProjectName(), "零件名称：", workOrder.getPartName()};
        String[] header1 = {"图号:", workOrder.getChartNumber(), "订单数量:", workOrder.getOderNumber().toString()};
        String[] header2 = {"序号", "工序", "工艺内容", "生产数量", "预估工时(h)", "操作员", "下工段接收确认", "备注"};
        //表尾
        String[] bottom = {"说明", "1、工序、工艺如有变更需经过工艺签字确认；", "2、工时有异议需要变更填写申请工时变更单，由班组长、工艺、生管、主管签字确认；", "3、所有数量要真实，准确移交双方要当面清点，移交后由接收人负责。"};

        //字段名
        String[] fieldNameArr = {"sequenceNumber", "productionProcesses", "processContent", "productionQuantity", "estimateTime", "operator", "receptionConfirmation", "remarks"};
        //路径
        String path = "E:\\ideaShengchanguanli\\ShengChanGuanLi\\excel";
        //文件名
        String fileName = currentTime + "-" + workOrder.getProductOrder().getProjectName() + "-" + workOrder.getPartName();
        //数据
        List<ProcessFlow> processFlowList = (List<ProcessFlow>) map.get("rows");

        ExportExcel<ProcessFlow> exportExcel = new ExportExcel<ProcessFlow>();
        //导出excel保存到本地,并弹出下载框

        exportExcel.exportExcel(bottom, title, header0, header1, header2, fieldNameArr, processFlowList, fileName, path, response);
        //打印本地的excel文件
    }

    @PostMapping(value = "processFlow/import")
    @ResponseBody
    public Map<String, Object> importProcessFlows(@RequestParam(value = "file") MultipartFile file) {
        //由采购订单xls导入、增加到工单表内
        Map<String, Object> map = new HashedMap();
        try {
            if (null != file) {
                importExcel(file);
                map.put("msg", "success");
            } else {
                map.put("msg", "fail");
            }
        } catch (Exception e) {
            map.put("msg", e.getMessage());
        }
        return map;
    }

    /**
     * @param file
     * @author cRyann
     * @Description 客制xls导入方法
     **/
    public void importExcel(MultipartFile file) {

        ImportParams params = new ImportParams();
        SimpleDateFormat format = new SimpleDateFormat("yyyy.M.dd");
        try {
            File f = FileUtils.copeMultipartFile(file, "D://excel//");
            file.transferTo(f);
            Workbook work = ExcelUtil.getWorkbook(file.getInputStream(), file.getOriginalFilename());
            if (null == work) throw new Exception("创建Excel工作薄为空！");
            //获取表头
            String projectNumber = (String) ExcelUtil.getCellValue(work, 0, 4, 5);
            ProductOrder po = productOrderService.findByProjectNumber(projectNumber);
            if (null == po) {
                po = new ProductOrder();
                po.setApplicationSector((String) ExcelUtil.getCellValue(work, 0, 3, 2));
                po.setProjectName((String) ExcelUtil.getCellValue(work, 0, 3, 5));
                po.setDateOfApplication(format.parse(ExcelUtil.getCellValue(work, 0, 3, 9).toString()));
                po.setCostCenterNumber((String) ExcelUtil.getCellValue(work, 0, 4, 2));
                po.setProjectNumber((String) ExcelUtil.getCellValue(work, 0, 4, 5));
                po.setUnit((String) ExcelUtil.getCellValue(work, 0, 4, 8));
                po.setNumberSign((String) ExcelUtil.getCellValue(work, 0, 4, 9));
            }
            productOrderService.save(po);
            //获取列表
            params.setTitleRows(5);
            params.setHeadRows(1);
            params.setLastOfInvalidRow(2);
            List<Map<String, Object>> mapList = new ExcelContrller().ImportExcel(f, params);
            for (Map<String, Object> map : mapList) {
                WorkOrder wo = new WorkOrder();
                wo.setSerialNumber(String.valueOf(map.get("序号")));
                wo.setMaterialNumber((String) map.get("物料编号"));
                wo.setPartName(String.valueOf(map.get("零件名称")));
                wo.setMaterial(String.valueOf(map.get("材质")));
                wo.setMaterialSpec(String.valueOf(map.get("原材料规格（长*宽*厚）")));
                wo.setChartNumber(String.valueOf(map.get("图纸编号")));
                wo.setOderNumber(String.valueOf(map.get("数量")));
                wo.setUnit(String.valueOf(map.get("单位")));
                wo.setArrivalDate(map.get("到货日期") == null ? null : format.parse(map.get("到货日期").toString()));
                wo.setRemarksFig(String.valueOf(map.get("备注/附图")));
                wo.setProductOrder(po);
                wo.setWorkOrderStatus(Not_Ready.toString());
//                wo.setProcessStatuses(processStatusService.findByStatusName(processInitStatus));
                workOrderService.save(wo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "processController/comboBoxData", method = RequestMethod.POST)
    @ResponseBody
    public List<Map<String,String>> findForComboBoxData() {
        List<Map<String,String>> list = new ArrayList<>();
        for (StatusEnum e : values()) {
            if (!e.toString().equals("Not_Ready")){
                Map<String,String> map = new HashMap<>();
                map.put("statusName",e.toString());
                list.add(map);
            }
        }
        return list;
    }
}

